/*新闻资讯列表*/
'use strict';
import React, {Component} from 'react';
import Header from '../common/header';
import styles from '../style/styles';
import * as URLconstant from '../constant/URLconstant';
import Util from '../common/util'
import Swiper from 'react-native-swiper'
import {
    View,
    Text,
    Image,
    ScrollView,
    TouchableOpacity,
    NativeModules,
    StyleSheet,
    FlatList
} from 'react-native';

export default class newsList extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.successGet = this.successGet.bind(this);
        this.errorGet = this.errorGet.bind(this)
        this.state = {
            newsList: null,
            page: 1,
            limit: 10,
            isOver: false,
            adList: [],
            imgHeightList: [],
            cate: [],
            loaded: false,
            cate_id: '',
            loadedList: false,
            hasNews: true
        };
        this.onEndReached = this.onEndReached.bind(this)
        this._renderRow = this._renderRow.bind(this)
        this.renderFooter = this.renderFooter.bind(this)
        this._renderHeader = this._renderHeader.bind(this)
    }


    componentDidMount() {
        let params = this.props.route.params
        if (params&&params.cate_id) {
            this.setState({
                cate_id: params.cate_id
            })
        }
        this.getAllNews();
        this.getAdZones()
    }

    componentWillUnmount() {

    }

    getAdZones() {
        let url = URLconstant.AD_ZONES
        let datakey = []
        datakey['adzones_type'] = 12
        datakey['user_id'] = ''
        Util.get(url, datakey, this.getAdZonesSuc.bind(this), this.errorGet)
    }

    getAdZonesSuc(datas) {
        if (datas.status == 0) {
            this.setState({
                adList: datas.data
            })
            this.getImgHeight(datas.data)
        }
    }


    async getImgHeight(urls) {
        try {
            let list = [];
            await urls.map((url, index) => {
                Image.getSize(url.source_url, (width, height) => {
                    let imgheight = Util.size.width * height / width;
                    list[index] = imgheight
                    if (list.length == urls.length) {
                        this.setState({
                            imgHeightList: list,
                        })
                    }
                }, (error) => {
                    LOG('图片路径错误。。。。。。。。' + error);
                })
            })
        } catch (err) {
            LOG(err);
        }
    }

    getAllNews() {

        let url = URLconstant.NEWSLIST_URL;
        let datakey = [];
        datakey['page'] = this.state.page
        datakey['limit'] = this.state.limit;
        if (this.state.cate_id) {
            datakey['cate_id'] = this.state.cate_id
        } else {
            datakey['cate_id'] = ''
        }
        Util.get(url, datakey, this.successGet, this.errorGet)
    }

    successGet(datas) {
        if (datas.status == 0) {
            let isOver = false
            let again = true
            let newsList = this.state.newsList;
            let newDatas = datas.data.article.list
            let cate = datas.data.cate
            let limit = this.state.limit
            if (newDatas.length < limit) {
                isOver = true
                again = false
            }
            let hasNews = true
            if (this.state.page == 1 && newDatas.length == 0) {
                hasNews = false
            }
            if(newsList==null){
                newsList=[]
            }
            Array.prototype.push.apply(newsList, newDatas);
            this.setState({
                isOver: isOver,
                again: again,
                newsList:newsList,
                cate: cate,
                loaded: true,
                loadedList: true,
                hasNews: hasNews
            })
        }else{
            this.setState({
                loaded:true,
                newsList:[]
            })
        }
    }


    errorGet(err) {
        LOG(err)
    }

    newsDetail(aid, title) {
        let that = this;
        this.props.navigation.push('NewsDetail',{
            aid:aid,
            title:title
        })
    }


    cateHeader() {
        let cate = this.state.cate
        if (cate.length == 0) {
            return false
        }
        let cate_id = this.state.cate_id
        return (
            <View style={{height: 40}}>
                <ScrollView horizontal={true} style={Styles.cate_header}>
                    <TouchableOpacity style={Styles.cate_item} onPress={() => this.selectCate('')}>
                        <Text style={cate_id == '' ? {fontSize: 14, color: "#f00"} : {
                            fontSize: 14,
                            color: "#333"
                        }}>全部</Text>
                    </TouchableOpacity>
                    {
                        cate.map((item, index) => {
                            return (
                                <TouchableOpacity style={Styles.cate_item} key={index}
                                                  onPress={() => this.selectCate(item.cate_id)}>
                                    <Text style={cate_id == item.cate_id ? {fontSize: 14, color: "#f00"} : {
                                        fontSize: 14,
                                        color: "#333"
                                    }}>{item.cate_name}</Text>
                                </TouchableOpacity>
                            )
                        })
                    }
                </ScrollView>
            </View>
        )
    }

    async selectCate(cate_id) {
        let loadedList = this.state.loadedList
        if (!loadedList) {
            return false;
        }
        await this.setState({
            cate_id: cate_id,
            newsList:null,
            page: 1,
            limit: 10,
            isOver: false,
            loadedList: false
        })
        this.getAllNews()
    }

    async onEndReached() {
        if (this.state.again) {
            await this.setState({
                page: this.state.page + 1
            })
            this.getAllNews()
        }
    }

    _renderRow=({item})=> {
        return (
            <TouchableOpacity
                onPress={()=>this.newsDetail(item.article_id,item.title)}
                style={styles.news_list_wrap} key={item.article_id}>
                <View style={styles.news_img}>
                    <Image
                        source={{uri: item.pictrue}}
                        resizeMode={'cover'}
                        style={styles.news_img}
                    />
                </View>
                <View style={styles.news_left}>
                    <Text numberOfLines={2} style={styles.news_txt1}>{item.title}</Text>
                    <Text numberOfLines={2} style={styles.news_txt2}>{item.profile}</Text>
                    <Text style={styles.news_txt3}>{item.add_time}</Text>
                </View>

            </TouchableOpacity>
        )
    }

    renderFooter() {
        return (
            <View style={{height: 30, alignItems: 'center', justifyContent: 'center'}}>
                <Text style={{fontSize: 12, color: "#969696"}}>{this.state.isOver ? "没有更多数据了" : "正在加载中"}</Text>
            </View>
        )
    }

    _renderHeader() {
        let adList = this.state.adList
        let imgHeightList = this.state.imgHeightList
        if (adList.length == 0) {
            return null
        }
        return (
            <Swiper
                showsButtons={false}
                autoplay={true}
                height={imgHeightList[0]}
            >
                {
                    adList.map((item, index) => {
                        return (
                            <Image
                                key={index}
                                source={{uri: item.source_url}}
                                resizeMode={'cover'}
                                style={{width: Util.size.width, height: imgHeightList[index]}}
                            />
                        )
                    })
                }
            </Swiper>
        )
    }


    render() {
        return (
            <View style={{flex: 1,backgroundColor:"#fff"}}>
                <Header navigation={this.props.navigation} title={'新闻资讯'}/>
                {
                    !this.state.loaded ?
                        <View style={{flex: 1}}>
                            {Util.loading()}
                        </View> :
                        <View style={{flex: 1}}>
                            {this.cateHeader()}
                            {
                                this.state.hasNews == false ?
                                    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                                        <Text>没有咨询</Text>
                                    </View> :
                                    <FlatList
                                        data={this.state.newsList}
                                        renderItem={this._renderRow}
                                        onEndReached={this.onEndReached.bind(this)}
                                        keyExtractor={item => item.article_id}
                                        ListFooterComponent={this.renderFooter}
                                        ListHeaderComponent={this._renderHeader}
                                    />
                            }

                        </View>
                }

            </View>
        )
    }
}
var Styles = StyleSheet.create({
    cate_header: {
        flexDirection: 'row',
        width: Util.size.width,
        height: 40,
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#e0e0e0"
    },
    cate_item: {
        height: 40,
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 15,
    }
})